import 'dart:io';

import 'package:appflutterhomeschool/api/api_service.dart';
import 'package:appflutterhomeschool/api/dio_utils.dart';
import 'package:appflutterhomeschool/common/common.dart';
import 'package:appflutterhomeschool/model/notification_model.dart';
import 'package:appflutterhomeschool/model/tab_model.dart';
import 'package:appflutterhomeschool/route/application.dart';
import 'package:appflutterhomeschool/route/routes.dart';
import 'package:appflutterhomeschool/ui/dialogs/prompt_dialog_widgets.dart';
import 'package:appflutterhomeschool/utils/sp_util.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import '../my_app_view_model.dart';

class NoticeViewModel extends ChangeNotifier {
  RefreshController refreshController;

  bool identity;
  int count = 0;
  BuildContext me;
  MyAppViewModel myAppViewModel;
  String titleName;
  String notificationType = "";
  bool unreadBool = false;

  String isRead = "";

  bool openScreen = false;
  List<NotificationModel> notificationList = [];

  List<TabModel> listTab = [
    TabModel("通知", true),
    TabModel("表单", false),
    TabModel("任务", false),
    TabModel("讨论", false),
  ];

  NoticeViewModel(this.me);

  initView() {
    refreshController = RefreshController(initialRefresh: false);
    myAppViewModel = Provider.of<MyAppViewModel>(me);
    this.identity = SpUtil.getBool("identity");
    titleName = myAppViewModel.name ?? "";
    //弹出对话框  判断学生或者老师是否有信息
    judgingData();
    notifyListeners();
  }

  judgingData() {
    if (identity) {
      //获取班级列表
      DioUtils.getInstance().post(ApiService.getClasses, {
        "token": Constant.getToken(),
      }, (successCallBack) {
        List list = successCallBack["data"]["class_list"];
        if (list.length == 0) {
          xianshiDialog();
        }
      }, (errorCallBack) {
        print("errorCallBack ======== $errorCallBack");
      });
    } else {
      //获取学生列表
      DioUtils.getInstance().post(ApiService.getStudents, {},
          (successCallBack) {
        List list = successCallBack["data"]["students"];
        if (list.length == 0) {
          xianshiDialog();
        }
      }, (errorCallBack) {
        print("errorCallBack ======== $errorCallBack");
      });
    }
  }

  xianshiDialog() {
    PromptDialogWidgets(me).showPromptDialog(
      title: '提示',
      content: '请添加学生信息/或班级',
      cencel: '不添加',
      sure: '去添加',
      cancelOnTap: () => exit(0),
      sureOnTap: () {
        Application().navigatePushToPage(me, Routes.studentInformationPage, {});
      },
    );
  }

  initData() async {
    if (myAppViewModel.identity) {
      Dio2Utils.getInstance().post(ApiService.teacherGetNotifications, {
        "cls_mapping_id":
            myAppViewModel?.studentInformationModel?.classMappingId,
        "notification_type": notificationType
      }, (successCallBack) {
        notificationList.clear();
        refreshController.refreshCompleted();
        List notificationsData = successCallBack["data"]["notifications_data"];
        notificationsData.forEach((element) {
          notificationList.add(NotificationModel.fromJson(element));
        });

        notifyListeners();
      }, (errorCallBack) {
        refreshController.refreshCompleted();
      });
    } else {
      var map = {
        "student_id": myAppViewModel?.studentInformationModel?.subjectId,
        //类型：String  必有字段  备注：学生id
        "is_read": isRead,
        //类型：String  可有字段  备注：已读(True)、未读(False)(筛选条件)
        "notification_type": notificationType
        //类型：String  可有字段  备注：通知类型（Notification\Form\Task\ChatRoom）(筛选条件）
      };
      Dio2Utils.getInstance().post(ApiService.parentGetNotifications, map,
          (successCallBack) {
        notificationList.clear();
        refreshController.refreshCompleted();
        List notificationsData = successCallBack["data"]["notifications_data"];
        notificationsData.forEach((element) {
          notificationList.add(NotificationModel.fromJson(element));
        });

        notifyListeners();
      }, (errorCallBack) {
        refreshController.refreshCompleted();
      });
    }
  }

  //是否开启筛选
  onTapOpenScreen() {
    openScreen = !openScreen;
    if (openScreen) {
      notificationType = "Notification";
//    备注：已读(True)、未读(False)(筛选条件)
      isRead = "False";
    } else {
      isRead = "";
      notificationType = "";
    }
    notificationList.clear();
    initData();
    notifyListeners();
  }

  //获取身份
  getIdentityApplication() async {
    this.identity = myAppViewModel.identity;
    titleName = myAppViewModel.name ?? "";
    notificationList.clear();
    initData();
    notifyListeners();
  }

  //列表点击事件
  itemOnTap(int index) {
    NotificationModel notificationModel = notificationList[index];
    if (notificationModel.notificationType == "Form") {
      ///进入表单页面
      if (identity) {
        Application().navigatePushToPage(me, Routes.formDetailsPage,
            {"notification_id": notificationModel.id});
      } else {
        PromptDialogWidgets(me).noticeItemButtomDialog(
            pageTag: 2,
            notificationModel: notificationModel,
            onTap: () {
              notificationList.clear();
              initData();
            });
      }
    } else if (notificationModel.notificationType == "Task") {
      //任务页面
      PromptDialogWidgets(me).noticeItemButtomDialog(
          pageTag: 1, notificationModel: notificationModel);
    } else if (notificationModel.notificationType == "Notification") {
      //通知
      PromptDialogWidgets(me).noticeItemButtomDialog(
          pageTag: 0,
          notificationModel: notificationModel,
          onTap: () {
            notificationList.clear();
            initData();
          });
    } else if (notificationModel.notificationType == "ChatRoom") {
      ///进入讨论页面
      Application().navigatePushToPage(
          me, Routes.discussPage, {"notification_id": notificationModel.id});
    }
  }

  tapModelOnTap(int index) {
    for (int i = 0; i < listTab.length; i++) {
      listTab[i].display = false;
    }
    listTab[index].display = true;
//    Notification\Form\Task\ChatRoom
    switch (index) {
      case 0:
        notificationType = "Notification";
        break;
      case 1:
        notificationType = "Form";
        break;
      case 2:
        notificationType = "Task";
        break;
      case 3:
        notificationType = "ChatRoom";
        break;
    }
    notificationList.clear();
    initData();
    notifyListeners();
  }

  //已读 未读 备注：已读(True)、未读(False)(筛选条件)
  unreadBoolOnTap() {
    unreadBool = !unreadBool;
    isRead = unreadBool ? "True" : "False";
    notificationList.clear();
    initData();
    notifyListeners();
  }

  //家长端确认按钮触发
  sureReedOnTap(index) {
    Dio2Utils.getInstance().post(
        ApiService.parentNotificationIsConfirmed,
        {
          "notification_record_id": notificationList[index].id,
          //类型：String  必有字段  备注：通知记录
          "student_id": myAppViewModel.studentInformationModel.subjectId
          //类型：String  必有字段  备注：学生id
        },
        (successCallBack) {},
        (errorCallBack) {});
  }

  void onRefresh() async {
    initData();
  }

  void onLoading() async {
//    await Future.delayed(Duration(milliseconds: 1000));
    refreshController.loadComplete();
  }
}
